var c = document.getElementById('c');
var ctx = c.getContext('2d');
var tween1,
    style = {
        loop: 1
    };
var img = document.createElement('img');
img.origin  = '';
img.onload = function(e) {
    c.width = this.width;
    c.height = this.height;
    ctx.drawImage(this, 0, 0);
    //绑定点击事件
    c.addEventListener('click', handleClick, false);
}
img.src = '../images/img_1.jpg';
document.body.appendChild(img);



//点击事件处理函数
function handleClick() {
    var result = style.loop === 1 ? -1 : 1;
    //设定缓动动画
    tween1 = new TWEEN.Tween(style).to({
        loop: result
    }, 600)
    .easing(TWEEN.Easing.Quartic.InOut)
    .onUpdate(function(obj) {
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.translate(c.width / 2 - c.width * obj.loop / 2, 0);
        ctx.scale(obj.loop, 1);
        ctx.drawImage(img, 0, 0);
        ctx.setTransform(1, 0, 0, 1, 0, 0); //精髓一步，暂时看不懂
    })
    .start();
    animate();
}

function animate() {
    var id = requestAnimationFrame(animate);
    var result = TWEEN.update();
    if(!result) cancelAnimationFrame(id);
}